<template>
  <div class="bg-white _p-20">
    <div class="fz-16 title linh-48">活动基础信息</div>
    <a-form-model
      class="_pt-10"
      ref="form"
      :model="form"
      :rules="rules"
      labelAlign="right"
      layout="horizontal"
      :labelCol="{
        xs: { span: 24 },
        sm: { span: 3 }
      }"
      :wrapperCol="{
        xs: { span: 24 },
        sm: { span: 12 }
      }"
    >
      <a-form-model-item label="活动标题:" prop="title">
        <a-input v-model="form.title" placeholder="请输入标题" :maxLength="40" :disabled="disableEditing">
          <template #suffix> {{ form.title ? form.title.length : 0 }}/40 </template>
        </a-input>
      </a-form-model-item>
      <a-form-model-item label="活动分类:" prop="activityCategoryId">
        <a-cascader
          v-model="form.activityCategoryId"
          :options="categoryList"
          :field-names="{ label: 'name', value: 'id', children: 'children' }"
          placeholder="请选择活动分类"
          :disabled="disableEditing"
        />
      </a-form-model-item>
      <a-form-model-item label="小程序活动封面:" prop="coverUrl">
        <UploadImg
          v-model="form.coverUrl"
          warehouse
          cropper
          :width="180"
          :height="105"
          :cropperEnlarge="2"
          :disabled="disableEditing"
        >
          <template #tips>600*350</template>
        </UploadImg>
      </a-form-model-item>
      <a-form-model-item label="活动分享封面:" prop="sharUrl">
        <UploadImg
          v-model="form.sharUrl"
          warehouse
          cropper
          :width="125"
          :height="100"
          :cropperEnlarge="2"
          :disabled="disableEditing"
        >
          <template #tips>500*400</template>
        </UploadImg>
      </a-form-model-item>
      <a-form-model-item
        label="活动举办时间"
        required
        extra="活动结束24小时后将会进行资金结算，结算后会导致用户无法取消报名退费，请谨慎修改活动结束时间。"
      >
        <div class="disFlx">
          <a-form-model-item prop="startTime">
            <span v-if="disableEditing">{{ form.startTime }}</span>
            <FlatDateTimePicker
              v-else
              v-model="form.startTime"
              :maxDate="toggleDate(form.endTime)"
              :exceedsUpdDate="true"
            />
          </a-form-model-item>
          <span class="_ml-10 _mr-10">-</span>
          <a-form-model-item prop="endTime" extra="活动结束时间不可小于活动开始时间">
            <span v-if="disableEditing">{{ form.endTime }}</span>
            <FlatDateTimePicker
              v-else
              v-model="form.endTime"
              :minDate="toggleDate(form.startTime)"
              :exceedsUpdDate="true"
            />
          </a-form-model-item>
        </div>
      </a-form-model-item>

      <a-form-model-item
        label="活动报名时间:"
        prop="enrollTimeType"
        extra="报名结束时间需大于开始时间并且小于活动举办结束时间"
      >
        <a-radio-group
          v-model="form.enrollTimeType"
          :options="Dict.getLocalMap('BuyTimeTypeEnumDict', 'label', 'value')"
          :disabled="disableEditing"
        ></a-radio-group>
        <div v-if="form.enrollTimeType === BuyTimeTypeEnum.custom" class="disFlx">
          <a-form-model-item prop="enrollStartTime">
            <span v-if="disableEditing">{{ form.enrollStartTime }}</span>
            <FlatDateTimePicker
              v-else
              v-model="form.enrollStartTime"
              :minDate="toggleDate(info.createTime || moment().format('YYYY-MM-DD HH:mm:ss'))"
              :maxDate="toggleDate(form.endTime)"
              :exceedsUpdDate="true"
            >
            </FlatDateTimePicker>
          </a-form-model-item>
          <span class="_ml-10 _mr-10">-</span>
          <a-form-model-item prop="enrollEndTime" extra="结束时间不可小于开始时间">
            <span v-if="disableEditing">{{ form.enrollEndTime }}</span>
            <FlatDateTimePicker
              v-else
              v-model="form.enrollEndTime"
              :minDate="toggleDate(form.enrollStartTime)"
              :maxDate="toggleDate(form.endTime)"
              :exceedsUpdDate="true"
            >
            </FlatDateTimePicker>
          </a-form-model-item>
        </div>
      </a-form-model-item>

      <a-form-model-item label="活动地址:">
        <span v-if="disableEditing">{{ form.activitySiteJson ? form.activitySiteJson.addressName : '' }}</span>
        <SSelect
          v-else
          :modelValue.sync="form.siteId"
          :options="siteList"
          placeholder="请选择活动地址"
          optionValue="id"
          optionTitle="addressName"
        >
          <template #prefix="{ item }">
            <a-icon type="edit" class="_mr-10 colorZS" @click.stop="openAddressModal('edit', item)" />
          </template>
          <template #footer>
            <div class="disFlx flexCenter _pt-8 _pb-8" style="background-color: #FFF;border-top: solid 1px #e5e5e5;">
              <a-button class="_ml-15" type="primary" size="small" @click="openAddressModal('add')">新增地址</a-button>
            </div>
          </template>
        </SSelect>
      </a-form-model-item>
      <a-form-model-item
        label="活动联系人:"
        prop="majorIds"
        extra="联系人用于在活动详情里面展示。若联系人为管理员，则可以接收活动报名审核提醒"
      >
        <span v-if="disableEditing">
          <a-tag v-for="(user, index) in form.activityContactJson" :key="index"
            >{{ user.userName }}（{{ user.phonenumber }}）</a-tag
          >
        </span>
        <SSelect
          v-else
          mode="multiple"
          :modelValue.sync="form.majorIds"
          :options="attache_list"
          placeholder="请选择活动联系人"
          allowClear
          optionValue="id"
          optionTitle="name"
          :disabled="disableEditing"
        >
          <template v-if="!disableEditing" #prefix="{ item }">
            <a-icon type="edit" class="_mr-10 colorZS" @click.stop="handleShowAddContactModal(item, 'edit')" />
          </template>
          <template #suffix="{ item }">
            <span>（{{ item.phone }}）</span>
          </template>
          <template #footer>
            <div class="disFlx flexCenter _pt-8 _pb-8" style="background-color: #FFF;border-top: solid 1px #e5e5e5;">
              <a-button type="primary" size="small" class="_ml-10" @click="handleShowChooseContactModal"
                >从管理员中选择</a-button
              >
              <a-button type="primary" size="small" class="_ml-10" @click="handleShowAddContactModal({}, 'add')"
                >新增联系人</a-button
              >
            </div>
          </template>
        </SSelect>
      </a-form-model-item>
      <a-form-model-item label="限制报名人数:">
        <SSwitch
          :modelValue.sync="form.enrollRestrict"
          checkedChildren="是"
          :checkedValue="1"
          unCheckedChildren="否"
          :unCheckedValue="0"
          :disabled="disableEditing"
        />
      </a-form-model-item>
      <a-form-model-item v-if="form.enrollRestrict" label="最大报名人数:" prop="maxNum">
        <a-input-number v-model="form.maxNum" :min="1" :max="90000" :disabled="disableEditing" /><span
          style="margin-left: 10px"
          >人</span
        >
      </a-form-model-item>
    </a-form-model>

    <!-- 选择活动地址 -->
    <SelectAddress ref="SelectAddress" @success="setAddress" />

    <!-- 新增、编辑联系人 -->
    <AddContactModal ref="addContactModal" @success="setNewAttache" />

    <!-- 选择管理员作为联系人 -->
    <ChooseContactModal ref="chooseContactModal" @success="setNewAttache" />
  </div>
</template>

<script>
import UploadImg from '@/components/UpFile/uploadImg'
import FlatDateTimePicker from '@/components/FlatDateTimePicker'
import SSwitch from '@/components/Switch'
import { getActivityCategoryTree, activitySiteList, ContactList } from '@/api/activity/activity'
import SelectAddress from '../selectAddress'
import AddContactModal from '../linkman/addContactModal.vue'
import ChooseContactModal from '../linkman/chooseContactModal.vue'
import { cloneDeep, isNumber, isString } from 'lodash-es'
import SSelect from '@/components/Select'
import moment from 'moment'
import { activityTypeEnum, ActivitySettlementStatusEnum, BuyTimeTypeEnum } from '@/enums/activity'
export default {
  components: {
    UploadImg,
    FlatDateTimePicker,
    SelectAddress,
    AddContactModal,
    ChooseContactModal,
    SSelect,
    SSwitch
  },
  props: {
    info: {
      type: Object,
      default: () => ({})
    }
  },
  watch: {
    info: {
      handler(nval) {
        if (nval.id) {
          const cpNval = cloneDeep(nval)
          const newForm = {}
          Object.keys(this.form).forEach(key => {
            newForm[key] = cpNval[key]
            if (key === 'activityCategoryId') {
              newForm[key] = [cpNval[key]]
            } else if (key === 'majorIds') {
              newForm[key] = cpNval[key] ? cpNval[key].split(',').map(v => Number(v)) : []
            } else if (key === 'enrollTimeType') {
              newForm[key] = cpNval[key] ? cpNval[key] : BuyTimeTypeEnum.activityEndTime
            } else if (key === 'enrollStartTime') {
              newForm[key] = cpNval[key] ? cpNval[key] : newForm['endTime'] || newForm['startTime']
            }
          })

          if (this.disableEditing) {
            // 协办方仅查看状态
            newForm.activitySiteJson =
              cpNval.activitySiteJson && isString(cpNval.activitySiteJson)
                ? JSON.parse(cpNval.activitySiteJson)
                : cpNval.activitySiteJson // 地址转换
            newForm.activityContactJson =
              cpNval.activityContactJson && isString(cpNval.activityContactJson)
                ? JSON.parse(cpNval.activityContactJson)
                : cpNval.activityContactJson // 活动联系人转换
          }

          // 当前级联组件不支持选中绑定参数为单级,回显时需查询分类详情,当前分类固定2级
          if (isNumber(cpNval.activityCategoryId)) {
            getActivityCategoryTree({ id: cpNval.activityCategoryId }).then(res => {
              const data = res.data[res.data.length - 1]
              newForm.activityCategoryId = [data.parentId, data.id]
            })
          }
          this.form = newForm
        }
      },
      deep: true,
      immediate: true
    },
    'form.enrollTimeType'() {
      this.$nextTick(() => {
        this.updateData()
      })
    },
    'form.enrollRestrict'() {
      this.$nextTick(() => {
        this.updateData()
      })
    },
    'form.maxNum'() {
      this.$nextTick(() => {
        this.updateData()
      })
    },
    'form.enrollStartTime'() {
      this.$nextTick(() => {
        this.updateData()
      })
    },
    'form.startTime'() {
      this.$nextTick(() => {
        this.updateData()
      })
    },

    // 监听活动结束时间,动态赋值给报名结束时间
    'form.endTime'() {
      this.$nextTick(() => {
        this.$refs.form.validateField('endTime')
        this.$refs.form.validateField('enrollEndTime')
        this.$refs.form.validateField('enrollStartTime')
        this.updateData()
      })
    },
    'form.enrollEndTime'() {
      this.$nextTick(() => {
        this.$refs.form.validateField('enrollEndTime')
        this.$refs.form.validateField('enrollStartTime')
        this.updateData()
      })
    },
    'form.majorIds'() {
      this.$nextTick(() => {
        this.$refs.form.validateField('majorIds')
      })
    }
  },
  computed: {
    disabled() {
      return this.info.activityType === activityTypeEnum.other_join // 协办方
    },
    disableEditing() {
      return (
        [
          ActivitySettlementStatusEnum.PROGRESS,
          ActivitySettlementStatusEnum.SUCCESS,
          ActivitySettlementStatusEnum.PART_SUCCESS
        ].includes(this.info.settleStatus) || this.disabled
      )
    }
  },
  data() {
    return {
      siteList: [], // 地址列表
      attache_list: [], // 联系人列表
      categoryList: [], // 分类列表
      BuyTimeTypeEnum,
      form: {
        id: undefined,
        title: undefined,
        activityCategoryId: [],
        coverUrl: undefined,
        sharUrl: undefined,
        startTime: moment().format('YYYY-MM-DD HH:00:00'),
        endTime: undefined,
        enrollTimeType: BuyTimeTypeEnum.activityEndTime,
        enrollStartTime: moment().format('YYYY-MM-DD HH:00:00'),
        enrollEndTime: undefined,
        siteId: undefined,
        majorIds: [],
        enrollRestrict: 0,
        maxNum: 1
      },
      rules: {
        title: [{ required: true, message: '请输入活动标题', trigger: ['blur', 'change'] }],
        activityCategoryId: [{ required: true, message: '请选择活动分类', trigger: ['blur', 'change'] }],
        coverUrl: [{ required: true, message: '请选择封面图', trigger: ['blur', 'change'] }],
        sharUrl: [{ required: true, message: '请选择活动海报', trigger: ['blur', 'change'] }],
        startTime: [{ required: true, message: '请选择活动举办开始时间', trigger: ['blur', 'change'] }],
        endTime: [{ required: true, message: '请选择活动举办结束时间', trigger: ['blur', 'change'] }],
        enrollEndTime: [{ required: true, message: '请选择报名结束时间', trigger: ['blur', 'change'] }],
        enrollStartTime: [{ required: true, message: '请选择报名开始时间', trigger: ['blur', 'change'] }],
        majorIds: [{ required: true, message: '请选择活动联系人', trigger: ['blur', 'change'] }],
        maxNum: [{ required: true, message: '请输入最大报名人数', trigger: ['blur', 'change'] }]
      },
      loading: false
    }
  },
  created() {
    this.getCategoryTree()
    this.getActivitySiteList()
    this.getAttacheList()
  },
  methods: {
    moment,
    updateData() {
      this.$emit('update', {
        enrollRestrict: this.form.enrollRestrict,
        maxNum: this.form.maxNum,
        startTime:
          this.form.enrollTimeType === BuyTimeTypeEnum.activityEndTime
            ? this.info.createTime || moment().format('YYYY-MM-DD HH:mm:00')
            : this.form.enrollStartTime,
        endTime:
          this.form.enrollTimeType === BuyTimeTypeEnum.activityEndTime ? this.form.endTime : this.form.enrollEndTime
      })
    },
    // 获取活动分类-树形
    async getCategoryTree() {
      const { data } = await getActivityCategoryTree()
      this.categoryList = data
    },
    //获取活动地址列表
    async getActivitySiteList() {
      const { data } = await activitySiteList({
        current: 1,
        pageSize: 100
      })
      this.siteList = data.records
    },
    // 打开新增地址弹窗
    openAddressModal(type, data) {
      this.$refs.SelectAddress.show({
        type,
        data
      })
    },
    // 新增活动地址
    async setAddress(id) {
      await this.getActivitySiteList()
      this.form.siteId = id
    },
    //获取活动联系人列表
    async getAttacheList() {
      let res = await ContactList()
      this.attache_list = res.data || []
    },
    //打开新增联系人弹窗
    handleShowAddContactModal(row, type) {
      this.$refs.addContactModal.openModel({
        row,
        type
      })
    },
    //从管理员中选择
    handleShowChooseContactModal() {
      this.$refs.chooseContactModal.openModel()
    },
    setNewAttache(id) {
      if (!this.form.majorIds) this.form.majorIds = []
      if (id && !this.form.majorIds.includes(id)) this.form.majorIds.push(id)
      this.getAttacheList()
    },
    toggleDate(time) {
      return time ? new Date(time) : null
    },

    async saveForm() {
      return new Promise((resolve, reject) => {
        this.$refs.form.validate(valid => {
          if (valid) {
            let params = cloneDeep(this.form)
            params.activityCategoryId = params.activityCategoryId[params.activityCategoryId.length - 1]
            params.majorIds = params.majorIds.join(',')
            resolve(params)
          } else {
            this.$nextTick(() => {
              const targetElement = document.querySelector('.has-error')
              console.log(targetElement)
              if (targetElement) {
                targetElement.scrollIntoView({ behavior: 'smooth', block: 'center' })
              }
            }, 100)
            reject('活动基础信息表单校验未通过')
          }
        })
      })
    }
  }
}
</script>

<style lang="less" scoped>
.title {
  color: #1d2129;
  border-bottom: solid 1px #e5e6eb;
}
</style>
